<template>
  <div class="ai-search">
    <div class="header-container">
      <div class="container-header">
        <h2>AI智能搜索</h2>
        <p>使用AI技术精准查找您需要的内容</p>
      </div>

      <div class="search-bar">
        <el-input
            v-model="searchContent"
            placeholder="请输入您想搜索的内容..."
            size="large"
            class="search-input"
            @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" :loading="searchLoading" class="search-btn">搜索</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <div class="results-wrapper">
      <div class="results-container" v-if="showResults">
        <div class="results-inner">
          <div class="results-header">
            <h3>搜索结果</h3>
            <span class="result-count">共找到 {{ total }} 条相关结果</span>
          </div>

          <div class="works-grid">
            <el-card
                v-for="work in works"
                :key="work.sId"
                class="work-card"
                shadow="hover"
                @click="handleWorkClick(work.sId)"
            >
              <div class="work-cover">
                <img
                    :src="getCoverUrl(work.sCoverImg)"
                    :alt="work.sTitle"
                    class="cover-image"
                    loading="lazy"
                >
              </div>
              <div class="work-info">
                <h3 class="work-title">{{ work.sTitle }}</h3>
                <div class="work-meta">
                  <span class="category">分类: {{ work.cgyName }}</span>
                  <span class="date">{{ formatDate(work.sCreateTime) }}</span>
                </div>
                <div class="work-meta">
                  <span class="author">作者: {{ work.uNickName || '未知' }}</span>
                  <span class="click">点击量: {{ work.sClick }}</span>
                </div>
              </div>
            </el-card>
          </div>

          <div class="empty-state" v-if="!loading && works.length === 0">
            <el-empty description="暂无搜索结果"></el-empty>
          </div>

          <div class="loading-state" v-if="loading">
            <el-icon class="is-loading" :size="50"><Loading /></el-icon>
            <p>AI正在努力搜索中...</p>
          </div>

          <div class="pagination-container" v-if="works.length > 0">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[8, 16, 24]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElCard, ElInput, ElButton, ElPagination, ElEmpty, ElIcon } from 'element-plus';
import { Search, Loading } from '@element-plus/icons-vue';
import {_axios} from '../api/index.js';
import {showFailToast} from "vant";

export default {
  name: 'AiSearch',
  computed: {
    Search() {
      return Search
    }
  },
  components: {
    ElCard,
    ElInput,
    ElButton,
    ElPagination,
    ElEmpty,
    ElIcon,
    Search,
    Loading
  },
  setup() {
    const router = useRouter();

    // 状态管理
    const searchContent = ref('');
    const currentPage = ref(1);
    const pageSize = ref(8);
    const works = ref([]);
    const total = ref(0);
    const loading = ref(false);
    const searchLoading = ref(false);
    const searchId = ref(null);
    const showResults = ref(false);

    // 获取AI搜索结果
    const fetchAiSearch = async (isNewSearch = false) => {
      try {
        loading.value = true;

        let response;
        if (isNewSearch || !searchId.value) {
          // 新搜索请求
          searchLoading.value = true;
          response = await _axios.post('/creation/ai-search', {
            content: searchContent.value
          }, {
            params: {
              pageNum: currentPage.value,
              pageSize: pageSize.value
            }
          });

          // 保存搜索ID用于后续翻页
          searchId.value = response.searchId;
        } else {
          // 使用已有搜索ID进行翻页
          response = await _axios.get('/creation/ai-list', {
            params: {
              searchId: searchId.value,
              pageNum: currentPage.value,
              pageSize: pageSize.value
            }
          });
        }

        // 更新数据
        works.value = response.list || works.value;
        total.value = response.total || total.value;
        showResults.value = true;
      } catch (error) {
        // 更新数据
        showFailToast('搜索失败，请稍后重试');
      } finally {
        loading.value = false;
        searchLoading.value = false;
      }
    };

    // 处理搜索
    const handleSearch = () => {
      if (!searchContent.value.trim()) {
        showFailToast('请输入搜索内容');
        return;
      }

      currentPage.value = 1;
      searchId.value = null;
      fetchAiSearch(true);
    };

    // 处理作品点击
    const handleWorkClick = (workId) => {
      router.push({
        name: 'CreationDetail',
        params: { sId: workId }
      });
    };

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString();
    };

    // 获取封面图片URL
    const getCoverUrl = (coverImg) => {
      if (!coverImg) {
        return 'https://images.unsplash.com/photo-1518837695005-2083093ee35b?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=80';
      }
      const baseURL = _axios.defaults.baseURL || '';
      const cleanBaseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL;
      return `${cleanBaseURL}/img/${coverImg}`;
    };

    // 分页事件处理
    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentPage.value = 1;
      fetchAiSearch();
    };

    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchAiSearch();
    };

    return {
      searchContent,
      currentPage,
      pageSize,
      works,
      total,
      loading,
      searchLoading,
      showResults,
      handleSearch,
      handleWorkClick,
      formatDate,
      getCoverUrl,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.ai-search {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  padding-bottom: 40px;
}

.header-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 40px 20px 30px;
  text-align: center;
}

.container-header h2 {
  font-size: 2.5rem;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 10px;
  background: linear-gradient(90deg, #3498db, #2ecc71);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.container-header p {
  font-size: 1.1rem;
  color: #7f8c8d;
  margin-bottom: 30px;
}

.search-bar {
  max-width: 700px;
  margin: 0 auto;
}

.search-input {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(52, 152, 219, 0.15);
}

.search-input :deep(.el-input-group__prepend) {
  background: white;
  border: none;
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: none;
  border: none;
  padding: 12px 20px;
  font-size: 1rem;
}

.search-btn {
  background: linear-gradient(90deg, #3498db, #2ecc71);
  color: white;
  border: none;
  padding: 12px 25px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
}

.results-wrapper {
  width: 100%;
  background: transparent;
}

.results-container {
  width: 100%;
  margin-top: 20px;
}

.results-inner {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 0 10px;
}

.results-header h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.result-count {
  color: #7f8c8d;
  font-size: 0.95rem;
}

.works-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  margin-bottom: 40px;
}

.work-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  border: none;
  background: white;
}

.work-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.work-cover {
  width: 100%;
  height: 180px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.work-card:hover .cover-image {
  transform: scale(1.05);
}

.work-info {
  padding: 20px;
}

.work-title {
  font-size: 1.1rem;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.work-meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.85rem;
  color: #7f8c8d;
  margin-top: 8px;
}

.work-meta span {
  display: flex;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.pagination-container :deep(.el-pagination) {
  --el-pagination-bg-color: white;
  --el-pagination-button-disabled-bg-color: white;
  --el-pagination-hover-color: #3498db;
}

.empty-state {
  padding: 80px 0;
  text-align: center;
}

.loading-state {
  padding: 60px 0;
  text-align: center;
  color: #7f8c8d;
}

.loading-state p {
  margin-top: 15px;
  font-size: 1.1rem;
}

.is-loading {
  animation: spin 1s linear infinite;
  color: #3498db;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式调整 */
@media (min-width: 1200px) {
  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
}

@media (max-width: 1199px) and (min-width: 992px) {
  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}

@media (max-width: 991px) and (min-width: 769px) {
  .works-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }

  .container-header h2 {
    font-size: 2.2rem;
  }
}

@media (max-width: 768px) {
  .works-grid {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .header-container {
    padding: 30px 15px 20px;
  }

  .container-header h2 {
    font-size: 1.8rem;
  }

  .container-header p {
    font-size: 1rem;
  }

  .results-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .work-card {
    flex-direction: column;
  }

  .work-cover {
    height: 160px;
  }

  .work-meta {
    flex-direction: column;
    gap: 5px;
  }

  .search-input {
    border-radius: 8px;
  }
}

@media (max-width: 480px) {
  .container-header h2 {
    font-size: 1.6rem;
  }

  .container-header p {
    font-size: 0.95rem;
  }

  .work-info {
    padding: 15px;
  }

  .work-title {
    font-size: 1rem;
  }
}
</style>